package cn.tedu.jdbc;

//JDBC增删改查
import org.junit.Test;
import java.sql.*;
import java.util.Scanner;

public class Test1 {

    @Test
    public void getSelect() throws Exception {
        //1.注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");//8版本的jar包
                      //遵循的协议：//本机ip地址：端口号/数据库名
        String url = "jdbc:mysql://localhost:3306/gdb2109";
        //2.连接数据库
        Connection con = DriverManager.getConnection(url, "root", "root");
        //3.获取传输器
        Statement st = con.createStatement();
        //4.返回结果集
        ResultSet rs = st.executeQuery("select * from user2");
        //使用executeQuery必然是查询sql语句
        //5.处理结果
        while(rs.next()){
                             //字段数/列数
            for (int i = 1; i <=3; i++) {
                Object a = rs.getObject(i);

                System.out.println(a);
            }
//            for (int i = 1; i <4; i++) {
//                System.out.println(rs.getString(i));
//            }

        }
    }

    @Test
    public void getInsert() throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver");
                    //遵循的协议：//本机ip地址：端口号/数据库名
        String url= "jdbc:mysql://localhost:3306/gdb2109";
        //连接数据库
        Connection con = DriverManager.getConnection(url, "root", "root");
        Statement st = con.createStatement();
        int i = st.executeUpdate("insert into user2 values(null,'java','11111')");


    }

    @Test
    public void getDelete() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/gdb2109";
        Connection con = DriverManager.getConnection(url, "root", "root");
//        Statement st = con.createStatement();
//        int i = st.executeUpdate("delete from user2 where id=7");
        int id =new Scanner(System.in).nextInt();
        String sql="delete from user2 where id=?";
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setInt(1,id);
        int i = ps.executeUpdate();



    }


    @Test
    public void getUpdate() throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/gdb2109";
        Connection con = DriverManager.getConnection(url, "root", "root");
        Statement st = con.createStatement();
        int i = st.executeUpdate("update user2 set name='java' where id=6");

    }

}
